package manager;

import org.hibernate.Query;
import org.hibernate.Session;
import pojo.PrisTeam1Comment;
import util.HibernateUtil;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import pojo.PrisTeam1Car;

public class CommentManager {

	public boolean deleteComment(int id) {
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			Query delete = session
					.createQuery("delete from PrisTeam1Comment p where id = :id");
			delete.setInteger("id", id);
			delete.executeUpdate();
			session.getTransaction().commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean createAndStoreComment(PrisTeam1Car prisTeam1Car, String text) {

		try {
			PrisTeam1Comment comment = new PrisTeam1Comment();
			comment.setPrisTeam1Car(prisTeam1Car);
			comment.setText(text);
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.save(comment);
			session.getTransaction().commit();
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public PrisTeam1Comment getCommentById(String id) {
		int intId;
		if (!id.isEmpty())
			intId = Integer.parseInt(id);
		else
			return null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(PrisTeam1Comment.class);
		crit.add(Restrictions.like("id", intId));
		PrisTeam1Comment comment = (PrisTeam1Comment) crit.uniqueResult();
		session.getTransaction().commit();

		return comment;
	}

	public List<PrisTeam1Comment> getAllComments() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		@SuppressWarnings("unchecked")
		List<PrisTeam1Comment> allComments = (List<PrisTeam1Comment>) session
				.createQuery("from PrisTeam1Comment").list();
		session.getTransaction().commit();

		return allComments;
	}

	@SuppressWarnings("unchecked")
	public List<PrisTeam1Comment> getAllCarComments(PrisTeam1Car car) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query comm = session
				.createQuery("from PrisTeam1Comment p where prisTeam1Car = :car");
		comm.setEntity("car", car);
		List<PrisTeam1Comment> allComments = comm.list();
		session.getTransaction().commit();

		return allComments;
	}

	public static void main(String[] args) {
		CommentManager cmm = new CommentManager();
		CarManager cm = new CarManager();
		PrisTeam1Car car = cm.getCarById("2");
		List<PrisTeam1Comment> coms = cmm.getAllCarComments(car);
		for (PrisTeam1Comment c : coms)
			System.out.println(c.getText());
	}
}
